<template>
  <div class="video-study-container">
    <div class="left-panel">
      <div class="course-title">
        <h2>{{ courseDetail.courseName || '课程名称' }}</h2>
      </div>
      <div class="chapter-list">
        <div
          v-for="(chapter, cIdx) in chapters"
          :key="chapter.chapterId"
          class="chapter-item"
        >
          <div 
            class="chapter-header" 
            :class="{ 'active': activeChapters.includes(chapter.chapterId) }"
            @click="toggleChapter(chapter.chapterId)"
          >
            <span class="chapter-index">{{ cIdx + 1 }}</span>
            <span class="chapter-name">{{ chapter.chapterName }}</span>
            <el-icon class="chapter-arrow" :class="{ 'is-active': activeChapters.includes(chapter.chapterId) }">
              <arrow-down />
            </el-icon>
          </div>
          <transition name="slide">
            <ul v-if="activeChapters.includes(chapter.chapterId)" class="video-list">
            <li
              v-for="(video, vIdx) in chapter.videos"
              :key="video.videoId"
                :class="{ 'active': currentVideo && currentVideo.videoId === video.videoId }"
              @click="playVideo(video, chapter)"
            >
                <div class="video-item-content">
                  <span class="video-index">{{ vIdx + 1 }}</span>
              <span class="video-name">{{ video.videoName }}</span>
                </div>
            </li>
          </ul>
          </transition>
        </div>
      </div>
    </div>
    <div class="right-panel-flex">
      <div class="video-player-flex">
        <template v-if="currentVideo && currentChapter && currentVideo.videoName">
          <h3 style="margin-bottom: 16px;">{{ currentChapter.chapterName }} - {{ currentVideo.videoName }}</h3>
          <video
            v-if="currentVideo.videoUrl"
            :src="currentVideo.videoUrl"
            controls
            autoplay
            style="width: 100%; max-width: 1200px; height: 80vh; min-height: 400px; border-radius: 16px; background: #000; object-fit: contain; display: block; margin: 0 auto;"
          />
          <div v-else style="color: #bbb; margin: 40px 0;">暂无视频资源</div>
        </template>
        <div v-else style="color: #bbb; margin: auto;">请选择左侧视频进行学习</div>
      </div>
      <!-- 悬浮箭头按钮 -->
      <div class="drawer-toggle-btn" @click="drawerVisible = true">
        <el-icon><ArrowLeft /></el-icon>
      </div>
      <!-- 右侧抽屉分析卡片 -->
      <el-drawer
        v-model="drawerVisible"
        direction="rtl"
        size="420px"
        :with-header="false"
        custom-class="analysis-drawer"
      >
        <div class="video-analysis-card" style="height: 100%;">
          <el-tabs v-model="activeTab" tab-position="bottom" class="analysis-tabs">
            <el-tab-pane label="章节速览" name="chapter">
              <el-button type="primary" @click="generateChapterSummary(currentVideo && currentVideo.videoUrl)" :loading="chapterLoading" style="margin-bottom: 16px;">
                生成章节速览
              </el-button>
              <div v-if="chapterLoading" style="margin-top: 20px;">分析中...</div>
              <div v-else-if="chapterResult && chapterResult.length" style="margin-top: 20px;">
                <div v-for="(item, idx) in chapterResult" :key="idx" style="margin-bottom: 16px;">
                  <div><b>{{ item.Headline }}</b></div>
                  <div>{{ item.Summary }}</div>
                  <div style="color: #888; font-size: 12px;">{{ item.Start }} - {{ item.End }}</div>
                </div>
              </div>
              <div v-else-if="chapterResult && !chapterResult.length" style="margin-top: 20px;">暂无数据</div>
            </el-tab-pane>
            <el-tab-pane label="要点提炼" name="keypoint">
              <el-button type="primary" @click="handleKeypointClick" :loading="keypointLoading" style="margin-bottom: 16px;">
                生成要点提炼
              </el-button>
              <div v-if="keypointLoading" style="margin-top: 20px;">
                <div class="analysis-progress">
                  <el-progress :percentage="progressPercent" :stroke-width="15"></el-progress>
                  <div class="progress-text">分析中... {{progressPercent}}%</div>
                </div>
              </div>
              <div v-else-if="keypointResult && (keypointResult.Keywords || keypointResult.KeySentences)">
                <div v-if="keypointResult.Keywords">
                  <b>关键词：</b>
                  <el-tag v-for="(kw, i) in keypointResult.Keywords" :key="i" style="margin-right: 8px;">{{ kw }}</el-tag>
                </div>
                <div v-if="keypointResult.KeySentences">
                  <b>关键句子：</b>
                  <div v-for="(sent, i) in keypointResult.KeySentences" :key="i">{{ sent.Text }}</div>
                </div>
              </div>
              <div v-else>暂无数据</div>
            </el-tab-pane>
            <el-tab-pane label="PPT提取" name="ppt">
              <el-button type="primary" @click="generatePptExtraction(currentVideo && currentVideo.videoUrl)" :loading="pptLoading" style="margin-bottom: 16px;">
                生成PPT提取
              </el-button>
              <div v-if="pptLoading" style="margin-top: 20px;">
                <div class="analysis-progress">
                  <el-progress :percentage="progressPercent" :stroke-width="15"></el-progress>
                  <div class="progress-text">分析中... {{progressPercent}}%</div>
                </div>
              </div>
              <div v-else-if="pptResult && pptResult.KeyFrameList && pptResult.KeyFrameList.length">
                <div v-for="(frame, i) in pptResult.KeyFrameList" :key="i" style="margin-bottom: 16px;">
                  <div><b>帧 #{{ frame.Id }}</b></div>
                  <img v-if="frame.FileUrl" :src="frame.FileUrl" style="max-width: 100%; max-height: 200px;" />
                  <div v-if="frame.Summary">摘要：{{ frame.Summary }}</div>
                </div>
              </div>
              <div v-else>暂无数据</div>
            </el-tab-pane>
            <el-tab-pane label="摘要总结" name="summary">
              <el-tabs v-model="summaryTab" tab-position="top" class="summary-tabs">
                <el-tab-pane label="思维导图" name="mindmap">
                  <el-button type="primary" @click="generateSummary('mindmap')" :loading="summaryLoading" style="margin-bottom: 16px; background: linear-gradient(45deg, #0062ff, #00e1ff); border: none; box-shadow: 0 0 15px rgba(0, 234, 255, 0.5);">
                    生成思维导图
                  </el-button>
                  <div v-if="summaryLoading" class="tech-loading-container">
                    <div class="tech-loading-circle"></div>
                    <div class="tech-loading-text">分析中...</div>
                  </div>
                  <div v-else-if="summaryResult && summaryResult.MindMapSummary" class="tech-mindmap-container">
                    <div v-for="(item, i) in summaryResult.MindMapSummary" :key="i" class="mindmap-tree">
                      <div class="mindmap-root-node">{{ item.Title }}</div>
                      <div class="mindmap-branches">
                        <div v-for="(topic, j) in item.Topic" :key="j" class="mindmap-branch">
                          <div class="mindmap-node">
                            <span class="node-title">{{ topic.Title }}</span>
                          </div>
                          <div class="mindmap-leaf">{{ topic.Content }}</div>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div v-else class="tech-empty-data">暂无数据</div>
                </el-tab-pane>
                <el-tab-pane label="问答回顾" name="qa">
                  <el-button type="primary" @click="generateSummary('qa')" :loading="summaryLoading" style="margin-bottom: 16px; background: linear-gradient(45deg, #0062ff, #00e1ff); border: none; box-shadow: 0 0 15px rgba(0, 234, 255, 0.5);">
                    生成问答回顾
                  </el-button>
                  <div v-if="summaryLoading" class="tech-loading-container">
                    <div class="tech-loading-circle"></div>
                    <div class="tech-loading-text">分析中...</div>
                  </div>
                  <div v-else-if="summaryResult && summaryResult.QuestionsAnsweringSummary" class="tech-summary-container">
                    <div v-for="(item, i) in summaryResult.QuestionsAnsweringSummary" :key="i" class="tech-qa-item">
                      <div class="tech-qa-question">Q: {{ item.Question }}</div>
                      <div class="tech-qa-answer">A: {{ item.Answer }}</div>
                    </div>
                  </div>
                  <div v-else class="tech-empty-data">暂无数据</div>
                </el-tab-pane>
                <el-tab-pane label="发言总结" name="speech">
                  <el-button type="primary" @click="generateSummary('speech')" :loading="summaryLoading" style="margin-bottom: 16px; background: linear-gradient(45deg, #0062ff, #00e1ff); border: none; box-shadow: 0 0 15px rgba(0, 234, 255, 0.5);">
                    生成发言总结
                  </el-button>
                  <div v-if="summaryLoading" class="tech-loading-container">
                    <div class="tech-loading-circle"></div>
                    <div class="tech-loading-text">分析中...</div>
                  </div>
                  <div v-else-if="summaryResult && summaryResult.ConversationalSummary" class="tech-summary-container">
                    <div v-for="(item, i) in summaryResult.ConversationalSummary" :key="i" class="tech-speech-item">
                      <div class="tech-speaker">{{ item.SpeakerName || ('发言者' + item.SpeakerId) }}</div>
                      <div class="tech-speech-content">{{ item.Summary }}</div>
                    </div>
                  </div>
                  <div v-else class="tech-empty-data">暂无数据</div>
                </el-tab-pane>
              </el-tabs>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-drawer>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { getCourseDetail, getChaptersByCourse, getChapterDetail } from '@/api/course'
import { ArrowLeft, ArrowDown } from '@element-plus/icons-vue'
import {
  createChaptersAnalysisTask, getChaptersAnalysis,
  createMeetingAssistanceTask, getMeetingAssistanceAnalysis,
  createPptExtractionTask, getPptAnalysis,
  createMindMapSummaryTask, createQuestionsAnsweringTask, createConversationalSummaryTask, getSummarizationAnalysis,
  getTaskStatus
} from '@/api/summarization'
import { ElMessage } from 'element-plus'

const route = useRoute()
const courseId = route.params.id
const courseDetail = ref({})
const chapters = ref([])
const activeChapters = ref([])
const currentVideo = ref(null)
const currentChapter = ref({})

const activeTab = ref('chapter')
const summaryTab = ref('mindmap')
const actionTextMap = {
  chapter: '生成章节速览',
  keypoint: '生成要点提炼',
  ppt: '生成PPT提取',
  summary: {
    mindmap: '生成思维导图',
    qa: '生成问答回顾',
    speech: '生成发言总结'
  }
}

// 拖拽分栏逻辑
const leftWidth = ref(600) // 初始左栏宽度
let dragging = false
let startX = 0
let startWidth = 0

function startDrag(e) {
  dragging = true
  startX = e.clientX
  startWidth = leftWidth.value
  document.addEventListener('mousemove', onDrag)
  document.addEventListener('mouseup', stopDrag)
}
function onDrag(e) {
  if (!dragging) return
  const delta = e.clientX - startX
  let newWidth = startWidth + delta
  if (newWidth < 320) newWidth = 320
  if (newWidth > 1000) newWidth = 1000
  leftWidth.value = newWidth
}
function stopDrag() {
  dragging = false
  document.removeEventListener('mousemove', onDrag)
  document.removeEventListener('mouseup', stopDrag)
}

// 章节速览tab状态
const chapterLoading = ref(false)
const chapterResult = ref(null)

// 要点提炼tab状态
const keypointLoading = ref(false)
const keypointTaskId = ref('')
const keypointStatus = ref('')
const keypointResult = ref(null)

// PPT提取tab状态
const pptLoading = ref(false)
const pptTaskId = ref('')
const pptStatus = ref('')
const pptResult = ref(null)

// 摘要总结tab状态
const summaryLoading = ref(false)
const summaryTaskId = ref('')
const summaryStatus = ref('')
const summaryResult = ref(null)

// 摘要总结子tab类型映射
const summaryTypeMap = {
  mindmap: createMindMapSummaryTask,
  qa: createQuestionsAnsweringTask,
  speech: createConversationalSummaryTask
}

// 添加进度显示状态
const progressPercent = ref(0)

function updateProgress(percent) {
  progressPercent.value = percent
}

function resetProgress() {
  progressPercent.value = 0
}

// 新增摘要生成函数
async function generateSummary(type) {
  if (!currentVideo.value || !currentVideo.value.videoUrl) {
    ElMessage.warning('请先选择视频')
    return
  }
  
  summaryLoading.value = true
  summaryResult.value = null
  resetProgress()
  
  try {
    // 1. 创建分析任务
    const createTask = summaryTypeMap[type]
    if (!createTask) {
      throw new Error('不支持的摘要类型')
    }
    
    const res = await createTask(currentVideo.value.videoUrl)
    if (res.code !== 0 && res.code !== 200) throw new Error(res.message || '任务创建失败')
    const taskId = res.data.taskId

    // 2. 轮询任务状态
    let status = res.data.status
    let retry = 0
    while (status !== 'COMPLETED' && status !== 'FAILED' && retry < 30) {
      updateProgress(Math.min(Math.floor(retry / 30 * 100), 95))
      await new Promise(r => setTimeout(r, 2000))
      const statusRes = await getTaskStatus(taskId)
      console.log('摘要任务状态:', statusRes)
      status = statusRes.data.status
      retry++
      if (status === 'FAILED') throw new Error(statusRes.data.errorMsg || '分析失败')
    }
    if (status !== 'COMPLETED') throw new Error('分析超时')
    updateProgress(100)

    // 3. 获取分析结果
    const resultRes = await getSummarizationAnalysis(currentVideo.value.videoUrl)
    // 兼容多种结构，健壮赋值
    let summarization = {}
    if (resultRes.code === 0 || resultRes.code === 200) {
      if (resultRes.data && resultRes.data.summarizationResult && resultRes.data.summarizationResult.Summarization) {
        summarization = resultRes.data.summarizationResult.Summarization
      } else if (resultRes.data && resultRes.data.Summarization) {
        summarization = resultRes.data.Summarization
      } else if (resultRes.data) {
        summarization = resultRes.data
      }
    }
    summaryResult.value = summarization
  } catch (e) {
    ElMessage.error(e.message || '生成摘要失败')
    summaryResult.value = {}
  } finally {
    summaryLoading.value = false
  }
}

// 轮询工具
let pollTimer = null
function pollTaskStatus(taskId, setStatus, onSuccess, onFail) {
  if (pollTimer) clearInterval(pollTimer)
  let attempts = 0
  const MAX_ATTEMPTS = 30 // 最多轮询30次，约90秒
  
  pollTimer = setInterval(async () => {
    attempts++
    if (attempts > MAX_ATTEMPTS) {
      clearInterval(pollTimer)
      pollTimer = null
      onFail('分析超时，请稍后再试')
      return
    }
    
    try {
      const res = await getTaskStatus(taskId)
      if (res.code === 0 && res.data) {
        setStatus(res.data.status)
        // 设置进度百分比
        const progressPercent = Math.min(Math.floor(attempts / MAX_ATTEMPTS * 100), 95)
        updateProgress(progressPercent)
        
        if (['COMPLETED', 'FAILED', 'INVALID'].includes(res.data.status)) {
          clearInterval(pollTimer)
          pollTimer = null
          if (res.data.status === 'COMPLETED') {
            updateProgress(100)
            onSuccess()
          } else {
            onFail(res.data.errorMsg || '分析失败')
          }
        }
      }
    } catch (error) {
      clearInterval(pollTimer)
      pollTimer = null
      onFail(error.message || '网络请求错误')
    }
  }, 3000)
}

async function generateChapterSummary(videoUrl) {
  chapterLoading.value = true
  chapterResult.value = null
  try {
    // 1. 创建分析任务
    const res = await createChaptersAnalysisTask(videoUrl)
    if (res.code !== 0 && res.code !== 200) throw new Error(res.message || '任务创建失败')
    const taskId = res.data.taskId

    // 2. 轮询任务状态
    let status = res.data.status
    let retry = 0
    while (status !== 'COMPLETED' && status !== 'FAILED' && retry < 30) {
      await new Promise(r => setTimeout(r, 2000))
      const statusRes = await getTaskStatus(taskId)
      status = statusRes.data.status
      retry++
      if (status === 'FAILED') throw new Error(statusRes.data.errorMsg || '分析失败')
    }
    if (status !== 'COMPLETED') throw new Error('分析超时')

    // 3. 获取分析结果
    const resultRes = await getChaptersAnalysis(videoUrl)
    // 兼容多种结构，健壮赋值
    let autoChapters = []
    if (resultRes.code === 200 && resultRes.data) {
      if (resultRes.data.autoChaptersResult && Array.isArray(resultRes.data.autoChaptersResult.AutoChapters)) {
        autoChapters = resultRes.data.autoChaptersResult.AutoChapters
      } else if (Array.isArray(resultRes.data.AutoChapters)) {
        autoChapters = resultRes.data.AutoChapters
      } else if (Array.isArray(resultRes.data)) {
        autoChapters = resultRes.data
      }
    }
    chapterResult.value = autoChapters
  } catch (e) {
    ElMessage.error(e.message || '生成失败')
    chapterResult.value = []
  } finally {
    chapterLoading.value = false
  }
}

async function handleKeypointClick() {
  if (!currentVideo.value || !currentVideo.value.videoUrl) {
    ElMessage.warning('请先选择视频')
    return
  }
  keypointLoading.value = true
  keypointResult.value = null
  resetProgress()
  
  try {
    // 1. 创建分析任务
    const res = await createMeetingAssistanceTask(currentVideo.value.videoUrl)
    if (res.code !== 0 && res.code !== 200) throw new Error(res.message || '任务创建失败')
    const taskId = res.data.taskId

    // 2. 轮询任务状态
    let status = res.data.status
    let retry = 0
    while (status !== 'COMPLETED' && status !== 'FAILED' && retry < 30) {
      updateProgress(Math.min(Math.floor(retry / 30 * 100), 95))
      await new Promise(r => setTimeout(r, 2000))
      const statusRes = await getTaskStatus(taskId)
      console.log('要点提炼任务状态:', statusRes)
      status = statusRes.data.status
      retry++
      if (status === 'FAILED') throw new Error(statusRes.data.errorMsg || '分析失败')
    }
    if (status !== 'COMPLETED') throw new Error('分析超时')
    updateProgress(100)

    // 3. 获取分析结果
    const resultRes = await getMeetingAssistanceAnalysis(currentVideo.value.videoUrl)
    // 兼容多种结构，健壮赋值
    let meetingAssistance = {}
    if (resultRes.code === 0 || resultRes.code === 200) {
      if (resultRes.data && resultRes.data.meetingAssistanceResult && resultRes.data.meetingAssistanceResult.MeetingAssistance) {
        meetingAssistance = resultRes.data.meetingAssistanceResult.MeetingAssistance
      } else if (resultRes.data && resultRes.data.MeetingAssistance) {
        meetingAssistance = resultRes.data.MeetingAssistance
      } else if (resultRes.data) {
        meetingAssistance = resultRes.data
      }
    }
    keypointResult.value = meetingAssistance
  } catch (e) {
    ElMessage.error(e.message || '生成要点提炼失败')
    keypointResult.value = {}
  } finally {
    keypointLoading.value = false
  }
}

function handleAction() {
  if (!currentVideo.value || !currentVideo.value.videoUrl) {
    ElMessage.warning('请先选择视频')
    return
  }
  if (activeTab.value === 'chapter') {
    // 章节速览
    chapterLoading.value = true
    chapterResult.value = null
    createChaptersAnalysisTask(currentVideo.value.videoUrl).then(res => {
      if (res.code === 0 && res.data) {
        chapterTaskId.value = res.data.taskId
        chapterStatus.value = res.data.status
        pollTaskStatus(
          chapterTaskId.value,
          s => chapterStatus.value = s,
          async () => {
            const resultRes = await getChaptersAnalysis(currentVideo.value.videoUrl)
            if (resultRes.code === 0 && resultRes.data) {
              chapterResult.value = resultRes.data.autoChaptersResult?.AutoChapters || []
            }
            chapterLoading.value = false
          },
          err => {
            chapterLoading.value = false
            ElMessage.error(err)
          }
        )
      } else {
        chapterLoading.value = false
        ElMessage.error(res.message || '提交失败')
      }
    })
  } else if (activeTab.value === 'keypoint') {
    // 要点提炼
    handleKeypointClick()
  } else if (activeTab.value === 'ppt') {
    // PPT提取
    pptLoading.value = true
    pptResult.value = null
    createPptExtraction(currentVideo.value.videoUrl)
  } else if (activeTab.value === 'summary') {
    // 摘要总结子tab
    summaryLoading.value = true
    summaryResult.value = null
    const createTask = summaryTypeMap[summaryTab.value]
    if (!createTask) {
      summaryLoading.value = false
      ElMessage.error('不支持的摘要类型')
      return
    }
    createTask(currentVideo.value.videoUrl).then(res => {
      if (res.code === 0 && res.data) {
        summaryTaskId.value = res.data.taskId
        summaryStatus.value = res.data.status
        pollTaskStatus(
          summaryTaskId.value,
          s => summaryStatus.value = s,
          async () => {
            const resultRes = await getSummarizationAnalysis(currentVideo.value.videoUrl)
            if (resultRes.code === 0 && resultRes.data && resultRes.data.summarizationResult?.Summarization) {
              summaryResult.value = resultRes.data.summarizationResult.Summarization
            }
            summaryLoading.value = false
          },
          err => {
            summaryLoading.value = false
            ElMessage.error(err)
          }
        )
      } else {
        summaryLoading.value = false
        ElMessage.error(res.message || '提交失败')
      }
    })
  }
}

const drawerVisible = ref(false)

onMounted(async () => {
  // 获取课程详情
  const detailRes = await getCourseDetail(courseId)
  if (detailRes.code === 0 || detailRes.code === 200) {
    courseDetail.value = detailRes.data
  }
  // 获取所有章节
  const chapterRes = await getChaptersByCourse(courseId)
  if (chapterRes.code === 0 || chapterRes.code === 200) {
    chapters.value = chapterRes.data || []
    // 获取每个章节下的视频
    for (const chapter of chapters.value) {
      const res = await getChapterDetail(chapter.chapterId)
      chapter.videos = (res.code === 0 || res.code === 200) ? (res.data.videos || []) : []
    }
    // 默认展开第一个章节
    if (chapters.value.length > 0) {
      activeChapters.value = [chapters.value[0].chapterId]
    }
    // 自动定位到 query.videoId
    const targetVideoId = route.query.videoId
    if (targetVideoId) {
      for (const chapter of chapters.value) {
        const found = chapter.videos.find(v => v.videoId == targetVideoId)
        if (found) {
          currentVideo.value = found
          currentChapter.value = chapter
          break
        }
      }
    }
  }
})

function playVideo(video, chapter) {
  currentVideo.value = video
  currentChapter.value = chapter
  // 自动生成章节速览
  if (video.videoUrl) {
    generateChapterSummary(video.videoUrl)
    // 同时生成PPT提取
    generatePptExtraction(video.videoUrl)
  }
}

// 添加自动触发PPT提取分析的函数
async function generatePptExtraction(videoUrl) {
  if (!videoUrl) {
    ElMessage.warning('请先选择视频')
    return
  }
  
  pptLoading.value = true
  pptResult.value = null
  resetProgress()
  
  try {
    // 1. 创建分析任务
    const res = await createPptExtractionTask(videoUrl)
    if (res.code !== 0 && res.code !== 200) throw new Error(res.message || '任务创建失败')
    const taskId = res.data.taskId

    // 2. 轮询任务状态
    let status = res.data.status
    let retry = 0
    while (status !== 'COMPLETED' && status !== 'FAILED' && retry < 30) {
      updateProgress(Math.min(Math.floor(retry / 30 * 100), 95))
      await new Promise(r => setTimeout(r, 2000))
      const statusRes = await getTaskStatus(taskId)
      console.log('PPT任务状态:', statusRes)
      status = statusRes.data.status
      retry++
      if (status === 'FAILED') throw new Error(statusRes.data.errorMsg || '分析失败')
    }
    if (status !== 'COMPLETED') throw new Error('分析超时')
    updateProgress(100)

    // 3. 获取分析结果
    const resultRes = await getPptAnalysis(videoUrl)
    // 兼容多种结构，健壮赋值
    let pptExtraction = {}
    if (resultRes.code === 0 || resultRes.code === 200) {
      if (resultRes.data && resultRes.data.pptExtractionResult && resultRes.data.pptExtractionResult.PptExtraction) {
        pptExtraction = resultRes.data.pptExtractionResult.PptExtraction
      } else if (resultRes.data && resultRes.data.PptExtraction) {
        pptExtraction = resultRes.data.PptExtraction
      } else if (resultRes.data) {
        pptExtraction = resultRes.data
      }
    }
    pptResult.value = pptExtraction
  } catch (e) {
    ElMessage.error(e.message || '生成PPT提取失败')
    pptResult.value = {}
  } finally {
    pptLoading.value = false
  }
}

// 在activeTab监听器中添加PPT提取的自动触发
watch(activeTab, (newVal) => {
  if (newVal === 'ppt' && currentVideo.value && currentVideo.value.videoUrl && !pptResult.value && !pptLoading.value) {
    generatePptExtraction(currentVideo.value.videoUrl)
  }
})

// 添加章节展开/折叠方法
function toggleChapter(chapterId) {
  if (activeChapters.value.includes(chapterId)) {
    activeChapters.value = activeChapters.value.filter(id => id !== chapterId)
  } else {
    activeChapters.value.push(chapterId)
  }
}
</script>

<style scoped>
.video-study-container {
  display: flex;
  min-height: 100vh;
  height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4ebf5 100%);
  font-family: 'Inter', 'Source Sans Pro', 'Microsoft YaHei', sans-serif;
}
.left-panel {
  width: 320px;
  background: #fff;
  padding: 0;
  border-right: 1px solid rgba(229, 231, 235, 0.7);
  min-height: 100vh;
  position: relative;
  overflow: hidden;
  box-shadow: 0 0 25px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
}
.course-title {
  padding: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(to right, #ebf2ff, #f9faff);
  border-bottom: 1px solid #e1e8ff;
  position: sticky;
  top: 0;
  z-index: 100;
}
.course-title h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #2c5dff;
  text-align: center;
}
.chapter-list {
  flex: 1;
  overflow-y: auto;
  padding: 12px 0;
}
.chapter-item {
  margin-bottom: 2px;
}
.chapter-header {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  transition: all 0.2s ease;
  border-left: 3px solid transparent;
}
.chapter-header:hover {
  background-color: #f6f9ff;
}
.chapter-header.active {
  background-color: #f0f5ff;
  border-left: 3px solid #2c5dff;
}
.chapter-index {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  background-color: #2c5dff;
  color: white;
  border-radius: 50%;
  font-size: 12px;
  margin-right: 12px;
  font-weight: 500;
}
.chapter-name {
  flex: 1;
  font-weight: 500;
  color: #333;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.chapter-arrow {
  transition: transform 0.3s ease;
  color: #99a9c9;
}
.chapter-arrow.is-active {
  transform: rotate(180deg);
  color: #2c5dff;
}
.slide-enter-active,
.slide-leave-active {
  transition: all 0.3s ease;
  max-height: 500px;
  overflow: hidden;
}
.slide-enter-from,
.slide-leave-to {
  max-height: 0;
  opacity: 0;
}
.video-list {
  list-style: none;
  padding: 0;
  margin: 0 0 0 16px;
}
.video-list li {
  border-left: 1px solid #e6e6e6;
  margin: 0;
  padding: 0;
  cursor: pointer;
  transition: background 0.2s ease;
}
.video-list li:hover {
  background-color: #f9faff;
}
.video-list li.active {
  background-color: #f0f5ff;
}
.video-list li.active .video-item-content {
  border-left: 2px solid #2c5dff;
}
.video-item-content {
  display: flex;
  align-items: center;
  padding: 10px 12px;
  margin-left: 4px;
  border-left: 2px solid transparent;
}
.video-index {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #e9efff;
  color: #2c5dff;
  border-radius: 50%;
  font-size: 12px;
  margin-right: 10px;
}
.video-name {
  flex: 1;
  font-size: 14px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.video-list li.active .video-name {
  color: #2c5dff;
  font-weight: 500;
}
.right-panel-flex {
  display: flex;
  flex-direction: row;
  height: 100%;
  background: #fff;
  border-radius: 0;
  box-shadow: 0 0 30px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  flex: 1;
}
.video-player-flex {
  min-width: 320px;
  width: 100%;
  padding: 16px 16px 16px 32px;
  border-right: 1px solid #e6e6e6;
  box-sizing: border-box;
  flex-shrink: 0;
  flex-grow: 1;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
}
.splitter {
  width: 6px;
  cursor: col-resize;
  background: #e6e6e6;
  transition: background 0.2s;
  z-index: 10;
}
.splitter:hover {
  background: #2c5dff;
}
.video-analysis-flex {
  min-width: 320px;
  padding: 32px 32px 32px 16px;
  overflow-y: auto;
  flex: 1;
  align-items: center;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}
.video-analysis-card {
  width: 100%;
  max-width: 420px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.07);
  padding: 0 0 24px 0;
  display: flex;
  flex-direction: column;
  flex: 1;
  margin-top: 0;
  margin-bottom: 0;
  justify-content: flex-start;
  overflow: auto;
  border: 1px solid rgba(229, 231, 235, 0.7);
}
.analysis-tabs {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
}
.summary-tabs {
  margin-top: 16px;
  --el-color-primary: #2c5dff;
}
.summary-tabs :deep(.el-tabs__item) {
  color: #6b7280;
}
.summary-tabs :deep(.el-tabs__item.is-active) {
  color: #2c5dff;
}
.summary-tabs :deep(.el-tabs__active-bar) {
  background-color: #2c5dff;
  box-shadow: 0 0 10px #2c5dff50;
}
.drawer-toggle-btn {
  position: absolute;
  top: 50%;
  right: 0;
  transform: translateY(-50%);
  background: #fff;
  border-radius: 50%;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  width: 38px;
  height: 38px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 1001;
  border: 1px solid #e6e6e6;
  transition: all 0.2s;
}
.drawer-toggle-btn:hover {
  background: #f0f5ff;
  box-shadow: 0 6px 16px rgba(44, 93, 255, 0.15);
}
.analysis-drawer {
  padding: 0;
  background: #fff;
  border-left: 1px solid rgba(229, 231, 235, 0.7);
}
.analysis-progress {
  width: 100%;
  text-align: center;
  margin: 20px 0;
}
.progress-text {
  margin-top: 8px;
  color: #2c5dff;
}
.tech-loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
}
.tech-loading-circle {
  width: 40px;
  height: 40px;
  border: 4px solid #2c5dff;
  border-top-color: transparent;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}
@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
.tech-loading-text {
  margin-top: 10px;
  color: #2c5dff;
}
.tech-summary-container {
  margin-top: 20px;
}
.tech-mindmap-container {
  margin-top: 20px;
  padding: 20px;
  overflow-x: auto;
}
.mindmap-tree {
  margin-bottom: 30px;
  position: relative;
}
.mindmap-root-node {
  font-weight: bold;
  color: #2c5dff;
  font-size: 1.2rem;
  background: #f0f5ff;
  padding: 10px 20px;
  border-radius: 8px;
  display: inline-block;
  margin-bottom: 25px;
  position: relative;
  box-shadow: 0 4px 15px rgba(44, 93, 255, 0.1);
  border: 1px solid rgba(44, 93, 255, 0.3);
}
.mindmap-branches {
  margin-left: 40px;
  position: relative;
}
.mindmap-branches::before {
  content: '';
  position: absolute;
  left: -20px;
  top: 0;
  height: 100%;
  width: 2px;
  background: linear-gradient(180deg, #2c5dff, rgba(44, 93, 255, 0.1));
}
.mindmap-branch {
  margin-bottom: 20px;
  position: relative;
}
.mindmap-branch::before {
  content: '';
  position: absolute;
  left: -20px;
  top: 15px;
  width: 20px;
  height: 2px;
  background: #2c5dff;
  box-shadow: 0 0 5px rgba(44, 93, 255, 0.2);
}
.mindmap-node {
  margin-bottom: 8px;
  position: relative;
}
.node-title {
  font-weight: bold;
  color: #2c5dff;
  font-size: 1rem;
  background: #f8faff;
  padding: 8px 15px;
  border-radius: 6px;
  display: inline-block;
  box-shadow: 0 4px 10px rgba(44, 93, 255, 0.08);
  border: 1px solid rgba(44, 93, 255, 0.2);
}
.mindmap-leaf {
  margin-left: 25px;
  padding: 8px 12px;
  color: #6b7280;
  position: relative;
  background: #f9fafc;
  border-radius: 4px;
  border-left: 2px solid rgba(44, 93, 255, 0.3);
}
.mindmap-leaf::before {
  content: '';
  position: absolute;
  left: -15px;
  top: 50%;
  width: 15px;
  height: 1px;
  background: rgba(44, 93, 255, 0.3);
}
.tech-empty-data {
  margin-top: 20px;
  color: #94a3b8;
  text-align: center;
}
.tech-qa-item {
  margin-bottom: 20px;
  background: #f8faff;
  padding: 15px;
  border-radius: 8px;
  border: 1px solid rgba(44, 93, 255, 0.1);
}
.tech-qa-question {
  font-weight: 600;
  color: #2c5dff;
  font-size: 1rem;
  margin-bottom: 10px;
}
.tech-qa-answer {
  color: #6b7280;
}
.tech-speech-item {
  margin-bottom: 16px;
  padding: 15px;
  background: #f8faff;
  border-radius: 8px;
  border-left: 3px solid #2c5dff;
}
.tech-speaker {
  font-weight: 600;
  color: #2c5dff;
  font-size: 1rem;
  margin-bottom: 8px;
}
.tech-speech-content {
  color: #6b7280;
}

:deep(.el-button--primary) {
  background-color: #2c5dff;
  border-color: #2c5dff;
}

:deep(.el-button--primary:hover), 
:deep(.el-button--primary:focus) {
  background-color: #1c4de0;
  border-color: #1c4de0;
}

:deep(.el-tabs__item) {
  color: #6b7280;
}

:deep(.el-tabs__item.is-active) {
  color: #2c5dff;
}

:deep(.el-tabs__active-bar) {
  background-color: #2c5dff;
}

:deep(.el-progress-bar__inner) {
  background-color: #2c5dff;
}
</style> 